// @author a
// @date
// @note
package utils

import (
	"authserver/global"
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/hex"
)

const Padding_Pkcs5 = "PKCS5"
const Padding_Pkcs7 = "PKCS7"

// @Title aesutil 加密
// @Description
// @Param  origData []byte 需要加密的数组，二进制
// @Param  key []byte 秘钥数组
// @Param  iv []byte 加盐密钥数组
// @Return
func AesEncryptNormal(origData, key []byte) string {
	block, err := aes.NewCipher(key)
	if err != nil {
		global.GVA_LOG.Error(err.Error())
		return ""
	}

	blockSize := block.BlockSize()
	origData = PKCS5Padding(origData, blockSize)

	//加盐
	blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
	crypted := make([]byte, len(origData))
	blockMode.CryptBlocks(crypted, origData)
	return hex.EncodeToString(crypted)
}

// @Title aesutil 解密
// @Description
// @Param  crypted []byte 解密数组
// @Param  crypted []key  秘钥数组
// @Param  iv []byte 加盐密钥数组
// @Return
func AesDecryptNormal(crypted string, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	cryptedBs, err := hex.DecodeString(crypted)
	if err != nil {
		return nil, err
	}

	blockSize := block.BlockSize()
	blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
	origData := make([]byte, len(cryptedBs))
	blockMode.CryptBlocks(origData, cryptedBs)

	origData = PKCS5UnPadding(origData)
	return origData, nil
}

// @Title PKCS5 补码
// @Description
// @Param
// @Return
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

// @Title PKCS5 反补码
// @Description
// @Param
// @Return
func PKCS5UnPadding(origData []byte) []byte {
	length := len(origData)
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}
